package com.ben.chatroom.session.dao.impl;

import com.ben.chatroom.common.util.JsonUtil;
import com.ben.chatroom.session.dao.SessionCacheDAO;
import com.ben.chatroom.session.entity.SessionCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

/**
 * @author huangyijun
 */
@Repository
public class SessionCacheRedisImpl implements SessionCacheDAO {

    private final StringRedisTemplate redisTemplate;
    private final String REDIS_PREFIX = "SessionCache:id:";

    public SessionCacheRedisImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    @Override
    public void save(SessionCache cache) {
        if (cache == null) {
            return;
        }

        String _cache = JsonUtil.pojoToJson(cache);
        String _key = REDIS_PREFIX + cache.getSessionId();

        redisTemplate.opsForValue().set(_key, _cache);

    }

    @Override
    public SessionCache get(String sessionId) {
        String _val = redisTemplate.opsForValue().get(REDIS_PREFIX + sessionId);
        if (!StringUtils.isEmpty(_val)) {
            return JsonUtil.jsobToPojo(_val, SessionCache.class);
        }


        return null;
    }

    @Override
    public void removeCache(String sessionId) {
        redisTemplate.delete(REDIS_PREFIX + sessionId);
    }
}
